package endcourseproject;

import java.util.ArrayList;
import lejos.nxt.Sound;

public class Common implements DataMessageListener 
{
	private static NXTBluetooth _instance = null;
	private static ArrayList< DataMessageListener > _listeners
		= new ArrayList< DataMessageListener >();	
	
	public static void Init()
	{
		if( _instance == null )
		{
			_instance = new NXTBluetooth(new Common());
		}
	}
	
	public static void error(byte id, Exception ex)
	{ 
		write(id, ex.getMessage());
	}
	
	public static void write(byte id, String text)
	{
		Init();
		
		DataMessage data = new DataMessage(id, text);
		
		_instance.sendMessage(data);
	}
 
	public static boolean angleMatch(int a1, int a2, int wikel_room)
	{
		// TODO: mIm not 100% procent sure on this :S
        int temp = 0;
        if (a1 + wikel_room > 360 && a2 < a1)
        {
            temp = (a1 + wikel_room) % 360;

            if (temp > a2)
            {
                return true;
            }
        }

        if (a1 - wikel_room < 0 && a1 < a2)
        {
            temp = a1 - wikel_room + 360;

            if (temp < a2)
            {
                return true;
            }
        }

        if (a1 > a2)
        {
            if (a1 - wikel_room < a2)
            {
                return true;
            }
        }
        else
        {
            return a1 + wikel_room > a2;
        }

        return false;        
	}

	@Override
	public void messageReceived(Object sender, DataMessage message)
	{
		Common.receive(sender, message);
	}
	
	public static void attachReceiver(DataMessageListener listener)
	{
		for(DataMessageListener ln : _listeners)
		{
			if( ln == listener )
			{
				return;
			}
		}
		
		_listeners.add(listener);
	}
	
	private static void receive(Object sender, DataMessage message)
	{
		for(DataMessageListener listener : _listeners)
		{
			listener.messageReceived(sender, message);
		}
	}
	
	public static void sleep(int ms)
	{
		try {
			Thread.sleep(ms);
		}
		catch (InterruptedException e) 
		{
			beep();
		}
	}
	public static void beep()
	{
		Sound.beep();
	}
}
